Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

95
Visualizações
How to drop null elements but not undefined when using `arr.flatMap((f) => f ?? [])`?

I've written a function that removes null values from an array:

const dropNull = <T,>(arr: T[]): T[] => {
    return arr.flatMap((f) => f ?? []); // depends >= ES2019
};

For example:

const myArr1 = ['foo', 'bar', 'baz', null]
const output1 = dropNull(myArr1) 
console.log(output1) // => ["foo", "bar", "baz"] 

However, I realized that it also removes undefined values.

const myArr2 = ['foo', 'bar', 'baz', null, undefined]
const output2 = dropNull(myArr2)
console.log(output2) // => ["foo", "bar", "baz"] 

Is there a way to just tweak the current dropNull() in order to remove null but not undefined? That is, I know I could have re-written the function as:

const dropNull2 = <T,>(arr:T[]): T[] => {
    return arr.filter(element => element !== null)
}

But I like the arr.flatMap((f) => f ?? []) style. Is there a small change to it so it will drop only null but not undefined?

TS playground

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the ternary operators instead

return arr.flatMap((f) => f === null ? [] : f);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda